# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

#mongodb
from config.gl import MONGO
from inc.dbmgr import DbMgr

class MongoKbookPipeline(object):

    _dbmgr = None

    def __init__(self):
    	pass

    def sharedb(self):
        if not self._dbmgr:
            self._dbmgr = DbMgr(host=MONGO["HOST"], port=MONGO["PORT"])
            self._dbmgr.use("kankindle")
            self._dbmgr.use_collection("books")
            return self._dbmgr
        else:
            return self._dbmgr

    def close_spider(self, spider):
        if self._dbmgr:
            self._dbmgr.close()

    def process_item(self, book, spider):
        itemdata = dict()
        for key in book.keys():
            itemdata[key] = book[key]
    
        retfind = self.sharedb().find_one(dict(name = book["name"]))
        if retfind:
            self.sharedb().remove(dict(name = book["name"]))
        self.sharedb().insert(itemdata)
